package yb.ecp.fast.user.web;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.constants.ActionLevel;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.Ref;
import yb.ecp.fast.infra.util.StringUtil;
import yb.ecp.fast.user.infra.AuthCode;
import yb.ecp.fast.user.infra.BasicController;
import yb.ecp.fast.user.infra.ErrorCode;
import yb.ecp.fast.user.service.ProfileService;
import yb.ecp.fast.user.service.VO.AccountPwdVO;
import yb.ecp.fast.user.service.VO.LockVO;
import yb.ecp.fast.user.service.VO.ProfileConditionVO;
import yb.ecp.fast.user.service.VO.ProfileVO;
import yb.ecp.fast.user.service.VO.RegMemberVO;
import yb.ecp.fast.user.service.VO.UserScoreVO;
import yb.ecp.fast.user.service.VO.UserVO;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static yb.ecp.fast.infra.constants.ActionLevel.INNER;

/**
 * Created by john on 2017/12/5.
 */
@RestController
@RequestMapping("/profile")
public class ProfileController extends BasicController
{
    @Autowired
    private ProfileService profileService;

    @RequestMapping(method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.User.ADD)
    @ApiOperation(value = "添加用户")
    public ActionResult add(@RequestBody ProfileVO profileVO, @RequestHeader(name = "x-user-id", required = false) String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        Ref<String> userIdRef = new Ref<>("");

        if (StringUtil.isNullOrSpace(profileVO.getSpaceId())) {
            String spaceId = profileService.item(userId).getSpaceId();
            profileVO.setSpaceId(spaceId);
        }

        ErrorCode err = profileService.insert(profileVO, userIdRef);
        return actionResult(err, userIdRef.get());
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询用户列表详细信息")
    public ActionResult detail(@RequestParam("userId") String userId) throws Exception
    {
        return actionResult(profileService.item(userId));
    }

    @RequestMapping(value = "/getLogin", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询登录用户信息")
    public ActionResult getLoginUser(@RequestHeader(name = "x-user-id", required = false) String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        return actionResult(profileService.queryLoginUser(userId));
    }


    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询个人信息")
    public ActionResult queryUserInfo(@RequestHeader(name = "x-user-id", required = false) String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        return actionResult(profileService.queryLoginUser(userId));
    }

    @RequestMapping(value = "/listByIds",method = RequestMethod.POST)
    @ApiOperation("根据用户ids 查询用户列表")
    @FastMappingInfo(needLogin = true)
    public ActionResult listByIds(@RequestParam("userids") String[] userids)
    {
        List<UserVO> list = profileService.listByIds(Arrays.asList(userids));
        return actionResult(list);
    }

    @RequestMapping(value = "/list4export", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询用户列表,排除操作人,不分页")
    public ActionResult list4export(@RequestBody ProfileConditionVO condition, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        List<UserVO> list = profileService.list(condition, userId);
        return actionResult(list);
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询用户列表,排除操作人")
    public ActionResult list(@RequestBody SearchCommonVO<ProfileConditionVO> condition, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        PageCommonVO pageCommonVO = profileService.list(condition, userId);
        return actionResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/listProfiles", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询用户列表，不排除操作人")
    public ActionResult listProfiles(@RequestBody SearchCommonVO<ProfileConditionVO> condition, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        PageCommonVO pageCommonVO = profileService.listProfiles(condition, userId);
        return actionResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.User.REMOVES)
    @ApiOperation(value = "批量删除用户")
    public ActionResult removeUsers(@RequestBody List<String> userIds, @RequestHeader(name = "x-user-id", required = false) String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        if (userIds.contains(userId)) {
            return actionResult(ErrorCode.CannotRemoveYouself);
        }

        return actionResult(profileService.removeByIds(userIds));
    }

    @RequestMapping(value = "/removeSelf", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.User.REMOVES)
    @ApiOperation(value = "注销用户")
    public ActionResult removeSelf(@RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        return actionResult(profileService.removeSelfById(userId));
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "修改个人信息（个人中心）")
    public ActionResult update(@RequestBody ProfileVO profileVO, @RequestHeader(name = "x-user-id", required = false) String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        profileVO.setUserId(userId);
        return actionResult(profileService.update(profileVO));
    }

    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.User.UPDATE_USER)
    @ApiOperation(value = "修改用户信息（用户管理）")
    public ActionResult updateUserInfo(@RequestBody ProfileVO profileVO) throws Exception
    {
        if (StringUtil.isNullOrEmpty(profileVO.getUserId()))
        {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(profileService.update(profileVO));
    }

    @RequestMapping(value = "/updateUserByAccount", method = RequestMethod.POST)
    @FastMappingInfo(actionLevel = INNER)
    @ApiOperation(value = "根据登录名修改用户信息")
    public ActionResult updateUserByAccount(@RequestBody ProfileVO profileVO) throws Exception
    {
        return actionResult(profileService.updateByAccount(profileVO));
    }


    @RequestMapping(value = "/updateLock", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.User.LOCKED)
    @ApiOperation(value = "用户禁用与启用")
    public ActionResult lock(@RequestBody LockVO lockVO)
    {
        return actionResult(profileService.updateLock(lockVO));
    }


    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true, actionLevel = ActionLevel.OAUHT2)
    @ApiOperation(value = "查询Oauth2个人信息")
    public ActionResult getUserInfo(@RequestHeader("x-app-id") String appId, @RequestHeader(name = "x-user-id", required = false) String userId) throws Exception {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        return actionResult(profileService.getUserInfo(appId, userId));
    }

    @RequestMapping(value = "/addUserWithAccount", method = RequestMethod.POST)
    @ApiOperation(value = "添加用户账号和密码(生成用户信息)")
    public ActionResult addUserWithAccount(@RequestBody AccountPwdVO accountPwdVO) throws Exception
    {
        Ref<String> userIdRef = new Ref<>("");

        ErrorCode insertCode = profileService.addUserWithAccount(accountPwdVO, userIdRef);
        return actionResult(insertCode, userIdRef.get());
    }

    @RequestMapping(value = "/userDetail", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户缓存信息")
    public ActionResult getUserDetail(@RequestParam("userId") String userId)
    {
        return actionResult(profileService.getUserCache(userId));
    }

    @RequestMapping(value = "/listAll", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询系统所有用户")
    public ActionResult listAll(@RequestBody SearchCommonVO<ProfileVO> condition, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        PageCommonVO pageCommonVO = profileService.listAll(condition, userId);
        return actionResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/listByWorkspace", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "查询工作空间下用户集合")
    public ActionResult listByWorkspace(@RequestBody SearchCommonVO<ProfileVO> condition)
    {
        PageCommonVO pageCommonVO = profileService.listByWorkspace(condition);
        return actionResult(pageCommonVO.getPageInfo());
    }


    @RequestMapping(value = "/regMember", method = RequestMethod.POST)
    @ApiOperation(value = "注册用户信息")
    public ActionResult regMember(@RequestBody RegMemberVO regMemberVO) {
        ErrorCode insertCode = profileService.regMember(regMemberVO);
        return actionResult(insertCode);
    }

    @RequestMapping(value = "getMobilesByDepts" , method = RequestMethod.GET)
    @ApiOperation(value = "根据部门编码集合获取部门下所有的用户的手机号")
    public ActionResult<List<String>> getProfileMobilesByDepts(@RequestParam("workSpaceId")String workSpaceId,@RequestParam("deptIds") List<String> deptIds){
        if(StringUtils.isEmpty(workSpaceId) || CollectionUtils.isEmpty(deptIds)){
            return actionResult(Collections.EMPTY_LIST);
        }
        List<String> mobilesByDepts = profileService.getMobilesByDepts(workSpaceId, deptIds);
        return actionResult(mobilesByDepts);
    }

    @RequestMapping(value = "/queryBy400Code", method = RequestMethod.GET)
    @FastMappingInfo(actionLevel = ActionLevel.CLIENT)
    public ActionResult<String> queryBy400Code(@RequestParam("code400") String code400){
        Ref<String> userIdRef = new Ref<String>("");
        ErrorCode ret = profileService.queryBy400Code(code400, userIdRef);
        return actionResult(ret, userIdRef.get());
    }


    @RequestMapping(value = "/setUserJobId", method = RequestMethod.POST)
    @ApiOperation(value = "设置用户岗位")
    public ActionResult setUserJobId(@RequestBody ProfileVO profileVO) throws Exception
    {
        return actionResult(profileService.setUserJobId(profileVO));
    }

    @RequestMapping(value = "/updateUserForWx", method = RequestMethod.POST)
    @ApiOperation(value = "微信小程序修改用户")
    public ActionResult updateUserForWx(@RequestBody ProfileVO profileVO) throws Exception
    {
        if(StringUtil.isNullOrEmpty(profileVO.getUserId()))
        {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(profileService.updateForWx(profileVO));

    }

    @RequestMapping(value = "/updateUserAvatorForWx", method = RequestMethod.POST)
    @ApiOperation(value = "微信小程序修改用户头像")
    public ActionResult updateUserAvatorForWx(@RequestBody ProfileVO profileVO) throws Exception
    {
        if(StringUtil.isNullOrEmpty(profileVO.getUserId()))
        {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(profileService.updateUserAvatorForWx(profileVO));

    }

    @RequestMapping(value = "/getUserScore", method = RequestMethod.POST)
    @ApiOperation(value = "获取用户积分")
    public ActionResult getUserScore(@RequestBody SearchCommonVO<UserScoreVO> condition, @RequestHeader(name = "x-user-id", required = false) String userId) {
        if (StringUtils.isBlank(userId)) {
            return actionResult(ErrorCode.NeedLogin);
        }
        PageCommonVO pageCommonVO = profileService.getUserScoreV1(condition, userId);
        return actionResult(pageCommonVO.getPageInfo());
//        return actionResult(profileService.getUserScore(userId));
    }

}
